package com.tul.exercise.base.swing.components;

import com.tul.exercise.base.swing.SwingConsole;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.lang.reflect.Constructor;

/**
 * @Description 《java编程思想》第22章 示例14：
 * <p>
 * 按钮组组件：
 **/
public class ButtonGroups extends JFrame {
    private static String[] ids = {"June", "Ward", "Beaver", "Wally", "Eddie", "Lumpy"};

    static JPanel makeBPanel(Class<? extends AbstractButton> kind, String[] ids) {
        JPanel jp = new JPanel();

        ButtonGroup bg = new ButtonGroup();
        String title = kind.getName();
        title = title.substring(title.lastIndexOf(".") + 1);

        jp.setBorder(new TitledBorder(title));

        for (String id : ids) {
            AbstractButton ab = new JButton("failed");

            try {
                Constructor ctor = kind.getConstructor(String.class);
                ab = (AbstractButton) ctor.newInstance(id);

            } catch (Exception e) {
                System.err.println("Can't create " + kind);
            }
            bg.add(ab);
            jp.add(ab);
        }

        return jp;
    }

    public ButtonGroups() {
        setLayout(new FlowLayout());

        add(makeBPanel(JButton.class, ids));
        add(makeBPanel(JToggleButton.class, ids));
        add(makeBPanel(JCheckBox.class, ids));
        add(makeBPanel(JRadioButton.class, ids));
    }

    public static void main(String[] args) {
        SwingConsole.run(new ButtonGroups(), 500, 350);
    }
}
